/*
 *  Copyright 2010 mazhao.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package shopping.model;

import org.apache.ibatis.session.SqlSession;
import shopping.commons.ModelObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author mazhao
 */
public class Product extends ProductData {

    /**
     * update existing product(remember history)
     *
     * @return
     */
    public boolean update() {
        String sqlKeyVersion = getClassName() + ".getNextProductVersionId";
        String sqlKeyCopy = getClassName() + ".copyProductToHistory";
        String sqlKeyUpdate = getClassName() + ".updateExistProduct";

        log.debug("sql key " + sqlKeyVersion);
        log.debug("sql key " + sqlKeyCopy);
        log.debug("sql key " + sqlKeyUpdate);

        if (autoTrans) {
            session = getSession();
        }

        // next version
        int version = (Integer) session.selectOne(sqlKeyVersion, this);

        // copy product to history
        session.update(sqlKeyCopy, this);

        // update my version
        this.setVersion(version);
        int ret = session.update(sqlKeyUpdate, this);

        if (autoTrans) {
            session.commit();
            session.close();
        }

        return ret == 1;
    }

    /**
     * delete existing product
     *
     * @return
     */
    public boolean delete() {
        String sqlKeyCopy = getClassName() + ".copyProductToHistory";
        String sqlKeyDelete = getClassName() + ".deleteExistProduct";
        if (autoTrans) {
            session = getSession();
        }
        // copy product to history
        session.update(sqlKeyCopy, this);
        // delete product
        int ret = session.delete(sqlKeyDelete, this);

        if (autoTrans) {
            session.commit();
            session.close();
        }
        return ret == 1;
    }

    // ============================================
    // static query method section
    // ============================================

    /**
     * <<<be sure not to use it in a transaction context>>>
     * select product for checkout.
     *
     * @param productId the id of the product to be selected
     * @return the product
     */
    public static Product getProductForCheckout(int productId) {
        String sqlKey = Product.class.getName() + ".getProductForCheckout";
        staticLog.debug("sql key for getProductForCheckout is " + sqlKey);
        SqlSession session = getSession();

        Product product = (Product) session.selectOne(sqlKey, productId);

        session.close();
        return product;
    }

    /**
     * <<<be sure not to use it in a transaction context>>>
     * get all products of the specified catalog id.
     *
     * @param catalogId
     * @return
     */
    public static List<Product> getAllProductsOfCatalog(int catalogId) {
        String sqlKey = Product.class.getName() + ".selectProductWithCatalogId";
        staticLog.debug("sql key " + sqlKey);
        SqlSession session = getSession();

        List<Product> products = session.selectList(sqlKey, catalogId);

        session.close();

        return products;
    }

    public static List<Product> getLimitProductsOfCatalog(int catalogId) {
        String sqlKey = Product.class.getName() + ".getLimitProductsOfCatalog";
        staticLog.debug("sql key " + sqlKey);
        SqlSession session = getSession();

        List<Product> products = session.selectList(sqlKey, catalogId);

        session.close();

        return products;
    }

    public static Map<String, List<Product>> getLimitProductForEachCatalog() {
        Map<String, List<Product>> map = new HashMap<String, List<Product>>();
        List<Catalog> allCat = Catalog.selectAllCatalog();
        for(Catalog c : allCat) {
            StringBuilder fullName = new StringBuilder();
            List<Catalog> pathToMe = c.pathToMe();
            for(Catalog ptc : pathToMe) {
                fullName.append(ptc.getName()).append(" > ");
            }

            List<Product> limitPro = getLimitProductsOfCatalog(c.getId());
            if(limitPro != null && limitPro.size() > 0) {
                map.put(fullName.toString(), limitPro);
            }
        }

        return map;
    }

}
